/**
 * 
 */
package com.xuetang9.demo.ssm.web;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.Page;
import com.xuetang9.demo.ssm.common.ValidationUtis;
import com.xuetang9.demo.ssm.common.request.DataTableRequest;
import com.xuetang9.demo.ssm.common.response.DataTableResponse;
import com.xuetang9.demo.ssm.domain.Resource;
import com.xuetang9.demo.ssm.domain.User;
import com.xuetang9.demo.ssm.service.UserService;

/**
 * @功能
 * @作者 闫健舒
 * @时间 2018年9月11日 上午9:49:28
 * @版本 ver 1.0.0
 */
@Controller
public class UserController {
	@Autowired
	private UserService  userService;
	@RequestMapping(path="/user/add")
	public String  list() {
		
		return "user/add";
	}
	
	@RequestMapping(path="/system/user.json")
	@ResponseBody // 自动把返回数据变成JSON格式
	public Object listJSON(@RequestBody DataTableRequest dataTableRequest) {
		DataTableResponse<User> json = new DataTableResponse<>();
		// draw接收到客户端的请求，原样返回
		json.setDraw(dataTableRequest.getDraw());
		// 计算当前的页码
		int pageNum = dataTableRequest.getStart() / dataTableRequest.getLength() + 1;
		Page<User> page = userService.AllPage(pageNum, dataTableRequest.getLength());
		// 设置数据总条数
		json.setRecordsTotal(page.getTotal());
		json.setRecordsFiltered(page.getTotal());
		// 设置查询出来的数据
		json.setData(page.getResult());
		return json;
	}
	@RequestMapping(path = "/system/user/new",method=RequestMethod.GET)
	public String create() {
		return "user/new-user";
	}
	@RequestMapping(path = "/system/user/new",method=RequestMethod.POST)
	@ResponseBody
	public Map<String ,Object> create(@Validated User user, BindingResult bindingResult){
		
		Map<String, Object> json = new HashMap<String, Object>();
		
		if(bindingResult.hasErrors()) {
			json.put("success", false);
			json.put("message", ValidationUtis.bindResultToList(bindingResult) );
		}else {
			// 调用业务层
			json.put("success", true);
		}
		return json;
	}
	@RequestMapping(path = "/system/user/quit",method=RequestMethod.GET)
	public String quit() {
		return "user/new-user";
	}
}
